<template>
  <div>
    <base-modal
      class="material-apply-dialog-container"
      :default-style="true"
      :show.sync="visible"
      :title="title"
      width="900px"
      @closed="reset"
      append-to-body
    >
      <form-builder v-if="type === 'personalLibrary'" :is-validate-by-parent="false" :fields="fields" ref="form" :value="form" @update="update" class="warehouse-form">

        <template slot="warehouseId" slot-scope="{ field }">
          <form-item :label="$t('common.form.preview.materialReturn.label1')" class="warehouse-form-select">
            <form-select
              :placeholder="field.placeholder" 
              :field="field" 
              :source="warehouseList" 
              v-model="form.warehouseId" 
              @update="updateWareHouseId" 
              :clearable="false"/>
          </form-item>
        </template>

        <template slot="warehousePositionId" slot-scope="{ field }">
          <form-item :label="$t('common.form.preview.materialReturn.label2')" class="warehouse-form-select">
            <form-select
              :placeholder="field.placeholder" 
              :field="field" 
              :source="warehousePositionList" 
              v-model="form.warehousePositionId" 
              @update="updateWarehousePositionId" 
              :clearable="false"/>
          </form-item>
        </template>

      </form-builder>

      <el-form label-position="top" v-if="type === 'warehouse'" :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
        <el-form-item :label="$t('common.form.preview.materialReturn.label3')" prop="wareHouseIdAndPositionId" v-if="type === 'warehouse'">
          <Cascader 
            :key="CascaderKey"
            :props="propsConfig" 
            clearable
            v-model="ruleForm.wareHouseIdAndPositionId"
            :options="warehouseList" 
            @change="updataWareHouseIdAndPositionId"
          >
          </Cascader>
          
        </el-form-item>
      </el-form>
      <material-table-new-version
        ref="materialTableNewVersion"
        :field="field"
        :data="data"
        :colums="colums"
        :card="card"
        :border="true"
        :warehouse-id="form.warehouseId"
        :position-id="form.warehousePositionId"
        :warehouse-name="warehouseName"
        :position-name="positionName"
        @openSnDialog="openSnDialog"
        @input="materialTableInputHandler"
        :stripe="true"
      />

      <div class="btn-group">
        <el-button type="primary" icon="el-icon-plus" plain size="mini" @click="addPart">{{$t('common.base.makeSure')}}</el-button>
      </div>

      <div class="dialog-footer" slot="footer">
        <el-button :disabled="pending" @click="visible = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" :disabled="pending" @click="submit">{{$t('common.base.submit')}}</el-button>
      </div>
      <!-- end 出库方式 -->
    </base-modal>

    <!-- start sn弹窗 -->
    <material-sn-dialog ref="materialSnDialog" />
    <!-- end sn弹窗 -->
  </div>
</template>

<script>
/* api */
import * as WareHouseApi from '@src/api/WareHouseApi';
/* components */
import MaterialTableNewVersion from './MaterialTableNewVersion.vue';
import MaterialSnDialog from './MaterialSnDialog';
import Vue from 'vue'
import { Cascader } from 'element-ui'
Vue.component('Cascader', Cascader);
import _ from 'lodash'
import i18n from '@src/locales'
import { WarehousePositionLabelEnum } from '@model/enum/LabelEnum'
import { isEmpty } from '@src/util/type';

export default {
  name: 'material-apply-dialog',
  props: {
    field: {
      type: Object,
      default: () => ({})
    },
    card: {
      type: Object,
      default: () => ({})
    },
    task: {
      type: Object,
      default: () => ({})
    },
    value: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    return {
      propsConfig: {
        label:'text',
        value:'value',
        lazy: true,
        lazyLoad:this.lazyLoad
      },
      ruleForm:{
        wareHouseIdAndPositionId:[]
      },
      rules: {
        wareHouseIdAndPositionId: [
          { type: 'array', required: true, message: i18n.t('common.form.placeHolder.materialReturn.pla1'), trigger: 'change' },
        ]
      },

      pending: false,
      visible: false,
      data: [],
      params: {},
      outRepertoryType: 1,
      personalRepertory: undefined,
      title: '',
      type: '',
      form: {
        warehouseId: '',
        warehousePositionId: '',
        warehouse: {},
        warehouseLocation: {}
      },
      warehouseList: [],
      warehouseId: '',
      warehouseName: '',
      warehousePositionList: [],
      warehousePositionId: '',
      positionName: '',
      disabled: false,
      CascaderKey:0
    }
  },
  computed: {
    fields() {
      return [
        // {
        //   formType: 'select',
        //   fieldName: 'warehouseId',
        //   displayName: '仓库',
        //   placeholder: '请选择仓库',
        //   isNull: 0,
        //   disabled: this.disabled,
        //   setting: {}
        // },
        {
          formType: 'select',
          fieldName: 'warehousePositionId',
          displayName: i18n.t('common.form.preview.materialReturn.label2'),
          placeholder: i18n.t('common.placeholder.selectSomething', {0:i18n.t('common.form.preview.materialReturn.label2')}),
          isNull: 0,
          setting: {}
        }
      ]
    },
    /** 备件清单附加组件配置 */
    cardConfig() {
      return JSON.parse(this.card.config || '{}');
    },
    /** 是否开启个人备件库 */
    openPersonalRepertory() {
      return this.outRepertoryType === 1
    },
    /** 显示出库方式 */
    showApproveType() {
      return this.personalRepertory && (this.showOutRepertoryPerson || this.showOutRepertoryDirect);
    },
    /** 显示申领个人备件库 */
    showOutRepertoryPerson() {
      return (this.cardConfig.sparePartWhere || []).indexOf('taskOutRepertoryPerson') > -1;
    },
    /** 显示直接出库 */
    showOutRepertoryDirect() {
      return (this.cardConfig.sparePartWhere || []).indexOf('taskOutRepertoryDirect') > -1;
    },
    /**
    * @description 物料返还弹窗字段
    */
    colums() {
      // TODO 可能存在判断displayName的情况
      let fields = [
        {
          displayName: this.$t('common.form.preview.materialReturn.tableLabel1'),
          fieldName: 'name',
          formType: 'text'
        },
        {
          displayName: this.$t('common.form.preview.materialReturn.colum1'),
          fieldName: 'sn',
          formType: 'text'
        },
        {
          displayName: this.$t('common.form.preview.materialReturn.tableLabel4'),
          fieldName: 'property',
          formType: 'text'
        },
        {
          displayName: this.$t('common.form.preview.materialReturn.tableLabel5'),
          fieldName: 'snManage',
          formType: 'text',
          width: '110px'
        },
        {
          displayName: this.$t('common.form.preview.materialReturn.tableLabel11'),
          fieldName: 'unit',
          width: '120px'
        },
        {
          displayName: this.$t('common.form.preview.materialReturn.colum2'),
          fieldName: 'number',
          width: '120px'
        },
        {
          displayName: this.$t('common.form.preview.materialReturn.tableLabel3'),
          fieldName: 'SN',
          fixed: 'right'
        },
        {
          displayName: this.$t('common.base.operation'),
          fieldName: 'action',
          fixed: 'right'
        }
      ]

      // 设置备件名称列宽
      fields.forEach(field => {
        if (field.fieldName == 'name') {
          field.width = '150px';
        }
      })

      // 未开启个人备件库时 不显示个人库存
      // if (!this.personalRepertory) {
      //   fields = fields.filter(field => field.fieldName != 'personRepertoryCount');
      // }

      return fields;
    },
  },
  watch: {
    'visible'(newValue) {
      // if (!newValue) {
      //   this.reset()
      // }
    }
  },
  mounted() {
    // this.initForm()
  },
  methods: {
    // 获取仓位的多语言label
    getWarehousePositionLabel(name) {
      return WarehousePositionLabelEnum[name] || name
    },
    lazyLoad (node, resolve) {
      const { level, value } = node;
      // 动态节点
      const nodes = [];  
      if(level === 1){
        this.form.warehouseId = value
        this.getWarehousePositionList()
          .then((res) => {
            if (res.success) {
              let data = res?.data || []
              data.forEach(item => {
                let obj = {
                  text: this.getWarehousePositionLabel(item.name),
                  value: item.id,
                  leaf: node.level >= 1,  
                }
                nodes.push(obj);
              })
            }
            this.warehousePositionList = nodes
            // resolve 节点返回
            resolve(nodes);
          })
          .catch((error) => {
            throw error
          });
      }
    },
    getPersonalWarehouseList() {
      // 个人库数据
      WareHouseApi.getPersonalInventoryWarehouse()
        .then((result) => {
          
          if (result?.success) {
            let warehouse = result?.data.warehouse || {}
            let warehousePositionList = result?.data.warehousePositionList || []
            this.warehouseList.push({
              text: warehouse.name,
              value: warehouse.id
            })
            this.warehouseName = this.warehouseList[0].text
            this.form.warehouseId = this.warehouseList[0].value
            this.warehousePositionList = warehousePositionList.map(item => {
              return {
                text: this.getWarehousePositionLabel(item.name),
                value: item.id
              }
            })
            this.positionName = this.warehousePositionList[0]?.text
            this.form.warehousePositionId = this.warehousePositionList[0]?.value
          }
          
        }).catch(error => {
          console.error(error);
        })
    },
    getWarehouseList() {
      // 仓库
      WareHouseApi.getWarehouseSearch({ enabled: true })
        .then((result) => {
          
          if (result?.success) {
            let data = result?.data || []
            this.warehouseList = data.map(item => {
              return {
                text: item.name,
                value: item.id
              }
            })
          }

        }).catch(error => {
          console.error(error);
        })
    },
    getWarehousePositionList() {
      // 仓库 - 仓位
      let params = {
        enabled: true,
        warehouseId: this.form.warehouseId
      }
      return WareHouseApi.getWarehousePositionSearch(params)
    },
    updateWareHouseId({ newValue }) {
      this.form.warehouseId = newValue
      this.form.warehouse = this.warehouseList.find(item => item.value === newValue) || {}
      this.warehouseName = this.form.warehouse.text
      // 清空仓位
      // this.form.warehousePositionId = ''
      this.getWarehousePositionList()
    },
    updateWarehousePositionId({ newValue }) {
      this.form.warehousePositionId = newValue
      this.form.warehouseLocation = this.warehousePositionList.find((item) => item.value == newValue) || {}
      this.positionName = this.form.warehouseLocation.text
    },
    updataWareHouseIdAndPositionId(newValue){
      // 选择仓库仓位时，如果第二级没数据，则设置选中数据为空
      if (newValue.length == 1) {
        this.ruleForm.wareHouseIdAndPositionId = []
        return
      }
      this.form.warehouseId = newValue[0]
      this.form.warehouse = this.warehouseList.find(item => item.value === newValue[0]) || {}
      this.warehouseName = this.form.warehouse.text
      this.form.warehousePositionId = newValue[1]
      this.form.warehouseLocation = this.warehousePositionList.find((item) => item.value == newValue[1]) || {}
      this.positionName = this.form.warehouseLocation.text
    },
    openSnDialog(type) {
      this.$refs.materialSnDialog.open(type)
    },
    /**
    * @description 切换出库方式
    */
    changeOutRepertoryType() {
      this.personalRepertory = {}
    },
    /**
    * @description 打开弹窗
    */
    open(typeMap) {
      let { title, type } = typeMap
      this.title = title
      this.type = type

      this.data = []
      this.warehouseList = []
      this.warehousePositionList = []
      this.form = {
        warehouseId: '',
        warehousePositionId: ''
      }
      this.ruleForm.wareHouseIdAndPositionId = []
      this.pending = false

      // 个人库
      if(this.type === 'personalLibrary') {
        this.disabled = true
        this.getPersonalWarehouseList()
      }
      // 仓库
      if(this.type === 'warehouse') {
        // 级联选择器，自增key，让级联选择器重新渲染，避免报错
        ++ this.CascaderKey
        this.getWarehouseList()
      }
      // 物料返还的列表数据
      const parentTableValue = _.cloneDeep(this.$parent.tableValue) 
      // 物料核销中的被替换物料数据
      let parentMaterialTableData = _.cloneDeep(this.$parent.materialTableData)
      // 如果被替换的物料中已经在列表中存在，则过滤掉
      parentMaterialTableData = parentMaterialTableData.map((item, index) => {
        if(item.snManage == '是' && parentTableValue.findIndex(item1=>{return item1.SN == item.SN}) > -1){
          parentTableValue.splice(parentTableValue.findIndex(item1=>{return item1.SN == item.SN}), 1)
          return null
        }else if(item.snManage == '否' && parentTableValue.findIndex(item1=>{return item.materialId == item1.id || item.id == item1.id}) > -1){
          parentTableValue.splice(parentTableValue.findIndex(item1=>{return item.materialId == item1.id || item.id == item1.id}), 1)
          return null
        }
        return item
      });


      
      parentMaterialTableData = parentMaterialTableData.filter(item=>{return !!item})
      this.data = parentMaterialTableData
      this.visible = true
      this.$nextTick(() => {
        if(this.data.length){
          this.data.forEach(item => {
            this.$refs.materialTableNewVersion.toggleSelection(item);
          });
        }else{
          // 默认添加一行数据
          this.addPart()
        }
      })

    },
    close() {
      this.visible = false
      this.reset()
    },
    /**
    * @description 添加备件
    */
    addPart() {
      this.$refs.materialTableNewVersion.add();
    },
    /**
    * @description 提交
    * @param {Object} formParams 添加物料
    */
    async submit() {
      // 获取物料数据
      let validateRes
      // 如果是仓库
      if(this.type === 'warehouse'){
        // 判断是否选择了仓库仓位
        this.$refs.ruleForm.validate((valid) => {
          validateRes = valid
        });
      }else{
        validateRes = await this.$refs.form.validate();
      }

      if (!validateRes) return;
      
      let tableData = this.getTableData()
      let isEmptys = tableData?.length == 1 && ( !tableData[0]?.id && !tableData[0]?.materialId )
      if (isEmptys) {
        this.$message.warning(this.$t('common.form.tip.materialReturn.tips8'))
        return
      }
      if(tableData?.some(item => item.isSnManage && isEmpty(item.SN))) {
        this.$message.warning(this.$t('common.validate.SNisNull'))
        return
      }
      // 过滤空数据，id 和 name 有一个不存在就当成空数据
      tableData = tableData.filter(item => item.id && item.name)
      // let snNotEnough = tableData.some(item => item.snManage === '是' && item.snList?.length !== item.number)
      // if(snNotEnough) {
      //   this.$message.warning('SN数量应与返还数量保持一致')
      //   return
      // }
      
      // tableData = tableData.filter(item => item.id)
      
      // 仓库仓位数据
      tableData = tableData.map((item) => {
        // TODO 国际化待办
        item.type = '物料返还'
        item.warehouseId = this.form.warehouseId
        item.warehouseName = this.warehouseName
        item.positionId = this.form.warehousePositionId
        item.positionName = this.positionName
        item.materialId = item.materialId ?? item.id
        item.name = item.materialName || item.name
        item.machine = item.machine
        return item
      })
      this.$emit('input', {
        data: tableData
      })
    },
    update({ field, newValue, oldValue }) {
      let { fieldName, displayName } = field
      if (this.$appConfig.debug) {
        console.info(`[FormBuilder] => ${displayName}(${fieldName}) : ${JSON.stringify(newValue)}`);
      }

      this.$set(this.form, fieldName, newValue)
    },
    arrayUnique(arr, name) {
      let hash = {};
      return arr.reduce(function (item, next) {
        hash[next[name]] ? '' : hash[next[name]] = true && item.push(next);
        return item;
      }, []);
    },
    initForm() {
      this.form = {
        warehouseId: '',
        warehousePositionId: '',
        warehouse: {},
        warehouseLocation: {}
      }
      this.form.warehouseId = ''
      this.form.warehousePositionId = ''
      this.disabled = false
    },
    initTableData() {
      this.$refs.materialTableNewVersion.outsideSetTableData()
    },
    getTableData() {
      return this.$refs?.materialTableNewVersion?.outsideGetTableData() || []
    },
    reset() {
      this.initForm()
      this.initTableData()
    },
    materialTableInputHandler(data, type) {
      /**
       * 为了让用户自己添加的空数据，也默认选中，
       * type === 'add' 代表是添加操作
       * 用户添加的数据，默认存放在 data 数组里面最后一位。
       */
      let arr = this.$refs?.materialTableNewVersion?.multipleSelection || []
      if(type === 'add'){
        const lastVal = data.length ? data[ data.length - 1 ] : []
        arr.push(lastVal)
      }
      this.data = data
      this.$set(this, 'data', data)
      this.$nextTick(() => {
        if(arr?.length){
          arr.forEach(item => {
            this.$refs.materialTableNewVersion.toggleSelection(item);
          });
        }
      })
    }
  },
  components: {
    [MaterialTableNewVersion.name]: MaterialTableNewVersion,
    [MaterialSnDialog.name]: MaterialSnDialog
  }
}
</script>

<style lang="scss" scoped>
.material-apply-dialog-container {
  ::v-deep .base-modal-body {
    min-height: 228px;
    // padding: 16px 0 !important;
  }

  .demo-ruleForm {
    padding: 0 16px;
  }

  .material-apply-method-panel {
    padding: 0 16px 16px;

    .el-radio {
      color: $text-color-regular;
      margin-right: 24px;
    }
  }

  .btn-group {
    text-align: left;
    margin-top: 16px;
    // padding: 0 12px !important;

    .el-button {
      padding: 8px;
      border-radius: 4px;
    }
  }

  .warehouse-form {
    display: flex;
    justify-content: space-between;
    margin: 0;
    padding: 0;
    .warehouse-form-select {
      width: 50%;
      margin-right: 40px !important;
    }
  }
  
}
::v-deep .form-item label {
  width: 80px !important;
}
</style>